import { ForbiddenException, Injectable } from '@nestjs/common';
import { Video, VideoCategory } from './video.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { getConnection, In, Repository } from 'typeorm';
import { pagination } from '../utils/pagination';
import { Category } from '../category/category.entity';
import { VideoItem } from '../video-item/video-item.entity';

@Injectable()
export class VideoService {
  constructor(
    @InjectRepository(Video) private video: Repository<Video>,
    @InjectRepository(VideoItem) private videoItem: Repository<VideoItem>,
    @InjectRepository(VideoCategory)
    private videoCategory: Repository<VideoCategory>,
    @InjectRepository(Category) private category: Repository<Category>,
  ) {}

  // 查询视频列表
  async getVideoList(params) {
    const videoList: any = await this.video
      .createQueryBuilder('video')
      .getMany();
    for (const t of videoList) {
      const index: number = videoList.indexOf(t);
      const res = await this.videoCategory
        .createQueryBuilder('video')
        .where({ videoId: t.id })
        .getMany();
      videoList[index].category = res.map((c) => c.categoryId);
    }
    return videoList;
  }

  // 添加视频
  async addVideo(bodyData) {
    const {
      videoName,
      describe,
      shortDescribe,
      isMovies,
      bluesNumber,
      sort,
      cover,
    } = bodyData;
    if (!videoName)
      throw new ForbiddenException({
        message: '视频名称videoName不能为空!',
        code: 100,
      });
    if (!describe)
      throw new ForbiddenException({
        message: '视频描述describe不能为空!',
        code: 100,
      });
    if (!cover)
      throw new ForbiddenException({
        message: '视频封面cover不能为空!',
        code: 100,
      });
    if (!shortDescribe)
      throw new ForbiddenException({
        message: '视频简短描述shortDescribe不能为空!',
        code: 100,
      });
    try {
      await this.video.save({
        videoName,
        describe,
        shortDescribe,
        isMovies,
        bluesNumber,
        cover,
        sort: sort ? sort : 1,
        create_time: new Date(),
        updated_time: new Date(),
      });
      return [];
    } catch (e) {
      console.log('error:', e);
      throw new ForbiddenException({ message: '创建视频失败!', code: 100 });
    }
  }

  // 获取视频详情
  async getVideoDetail(params) {
    if (!params.id)
      throw new ForbiddenException({ message: '视频不存在!', code: 100 });
    try {
      return await this.video.findOne({
        where: { id: params.id },
      });
    } catch (e) {
      console.log('error:', e);
      throw new ForbiddenException({ message: '获取详情失败!', code: 100 });
    }
  }

  // 修改视频
  async editVideo(bodyData) {
    const { id, videoName, describe, shortDescribe, cover } = bodyData;
    if (!id)
      throw new ForbiddenException({ message: '视频id不能为空!', code: 100 });
    if (!videoName)
      throw new ForbiddenException({
        message: '视频名称videoName不能为空!',
        code: 100,
      });
    if (!describe)
      throw new ForbiddenException({
        message: '视频描述describe不能为空!',
        code: 100,
      });
    if (!cover)
      throw new ForbiddenException({
        message: '视频封面cover不能为空!',
        code: 100,
      });
    if (!shortDescribe)
      throw new ForbiddenException({
        message: '视频简短描述shortDescribe不能为空!',
        code: 100,
      });
    try {
      await this.video.update(id, bodyData);
      return [];
    } catch (e) {
      console.log('error:', e);
      throw new ForbiddenException({ message: '修改视频失败!', code: 100 });
    }
  }

  // 删除视频
  async deleteVideo(params) {
    const res = await this.videoItem.findOne({ where: { videoId: params.id } });
    if (res)
      throw new ForbiddenException({
        message: '该视频有子集不可以删除!',
        code: 100,
      });

    if (!params.id)
      throw new ForbiddenException({ message: '视频id不能为空!', code: 100 });
    try {
      await this.video.delete(params.id);
      return [];
    } catch (e) {
      console.log('error:', e);
      throw new ForbiddenException({ message: '删除视频失败!', code: 100 });
    }
  }

  // 添加视频分类
  async addVideoCategory(bodyData) {
    const { videoId, categoryId } = bodyData;
    if (!categoryId)
      throw new ForbiddenException({ message: '分类id不能为空!', code: 100 });
    if (!videoId)
      throw new ForbiddenException({ message: '视频id不能为空!', code: 100 });

    const categoryResult = await this.category.findOne({
      where: { id: categoryId },
    });
    if (!categoryResult)
      throw new ForbiddenException({ message: '该分类不存在!', code: 100 });

    const videoResult = await this.video.findOne({
      where: { id: videoId },
    });
    if (!videoResult)
      throw new ForbiddenException({ message: '该视频不存在!', code: 100 });

    const videoCategory = await this.videoCategory
      .createQueryBuilder('videoCategory')
      .where({ videoId })
      .andWhere({ categoryId })
      .getMany();
    if (videoCategory.length > 0)
      throw new ForbiddenException({ message: '请勿重复添加!', code: 100 });

    try {
      await this.videoCategory.save({
        videoId,
        categoryId,
        create_time: new Date(),
        updated_time: new Date(),
      });
      return [];
    } catch (e) {
      console.log('error:', e);
      throw new ForbiddenException({ message: '添加分类失败!', code: 100 });
    }
  }

  // 删除视频分类
  async deleteVideoCategory(bodyData) {
    const { videoId, categoryId } = bodyData;
    if (!categoryId)
      throw new ForbiddenException({ message: '分类id不能为空!', code: 100 });
    if (!videoId)
      throw new ForbiddenException({ message: '视频id不能为空!', code: 100 });

    try {
      await getConnection()
        .createQueryBuilder()
        .delete()
        .from(VideoCategory)
        .where({ videoId })
        .andWhere({ categoryId })
        .execute();
      return [];
    } catch (e) {
      console.log('error:', e);
      throw new ForbiddenException({ message: '删除关联失败!', code: 100 });
    }
  }

  //  查询分类视频列表
  async getCategoryVideoList(params) {
    const videoCategoryResults = await this.videoCategory
      .createQueryBuilder('videoCategory')
      .select('videoCategory.videoId')
      .where({ categoryId: params.id })
      .getMany();
    const videoIdArr = videoCategoryResults.map((t) => t.videoId);

    const videoResults = await this.video
      .createQueryBuilder('video')
      .where({ id: In([...videoIdArr]) })
      .getMany();
    return videoResults;
  }
}
